<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  getConsultOrderPre,
  createConsultOrder,
  getConsultPayUrl
} from '@/api/consult'
import type { ConsultOrderPreData } from '@/types/consult'
import { useConsultStore } from '@/stores'
import type { Patient } from '@/types/user'
import { getPatient } from '@/api/user'
import { showFailToast } from 'vant'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import { showConfirmDialog } from 'vant'
const router = useRouter()
const store = useConsultStore()

const payInfo = ref<ConsultOrderPreData>()
const loadData = async () => {
  const res = await getConsultOrderPre({
    type: store.consult.type + '',
    illnessType: store.consult.illnessType + ''
  })

  payInfo.value = res.data
  // 把优惠券id，存储到仓库中
  store.setCouponId(res.data.couponId)
}

const patient = ref<Patient>()
const loadPatient = async () => {
  const res = await getPatient(store.consult.patientId!)
  patient.value = res.data
}

onMounted(() => {
  // 判断问诊信息是否还有，没有了跳转到首页
  if (
    !store.consult.illnessDesc ||
    !store.consult.patientId ||
    !store.consult.depId
  ) {
    router.push('/home')
  } else {
    loadData()
    loadPatient()
  }
})

const agree = ref(true)
// 控制选择支付面板
const show = ref(false)
const paymentMethod = ref<0 | 1>(1)
const orderId = ref('')
// 下单
const submit = async () => {
  if (!agree.value) return showFailToast('必须勾选协议')

  // 调用接口，生成订单，获取到订单id
  const res = await createConsultOrder(store.consult)
  orderId.value = res.data.id

  // 把本地问诊信息清空
  store.clear()

  // 让支付面板展示出来
  show.value = true
}
// 获取支付链接
const pay = async () => {
  const res = await getConsultPayUrl({
    paymentMethod: paymentMethod.value,
    orderId: orderId.value,
    payCallback: 'http://localhost/room'
  })

  // 打开支付链接即可
  window.location.href = res.data.payUrl
}
// 如果返回false则无法返回
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})

// 创建订单之后，关闭面板，要提示
const beforeClose = () => {
  showConfirmDialog({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭'
  })
    .then(() => {
      // on confirm
    })
    .catch(() => {
      // on cancel
      orderId.value = ''
      router.push('/user/consult')
    })
}
</script>

<template>
  <div class="consult-pay-page" v-if="payInfo">
    <cp-nav-bar title="支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payInfo.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payInfo.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payInfo.pointDeduction}`" />
      <van-cell
        title="实付款"
        :value="`¥${payInfo.actualPayment}`"
        class="pay-price"
      />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group v-if="patient">
      <van-cell
        title="患者信息"
        :value="`${patient.name} | ${patient.genderValue} | ${patient.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree"
        >我已同意 <span class="text">支付协议</span></van-checkbox
      >
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payInfo.actualPayment * 100"
      button-text="立即支付"
      text-align="left"
      @click="submit"
    />
    <van-action-sheet
      v-model:show="show"
      title="选择支付方式"
      :closeable="false"
      :before-close="beforeClose"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payInfo.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icon name="consult-wechat" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 0"
            /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icon name="consult-alipay" /></template>
            <template #extra
              ><van-checkbox :checked="paymentMethod === 1"
            /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay"
            >立即支付</van-button
          >
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }
      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }
  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }
  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    .text {
      color: var(--cp-primary);
    }
  }
  ::v-deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
    }
  }
  .pay-type {
    .amount {
      padding: 20px;
      text-align: center;
      font-size: 16px;
      font-weight: bold;
    }
    .btn {
      padding: 15px;
    }
    .van-cell {
      align-items: center;
      .cp-icon {
        margin-right: 10px;
        font-size: 18px;
      }
      .van-checkbox :deep(.van-checkbox__icon) {
        font-size: 16px;
      }
    }
  }
}
</style>
